package top.xia17.plugins.fast.auth.login;

import top.xia17.plugins.fast.common.autoconfiguration.TokenProperties;
import top.xia17.plugins.fast.common.database.redis.RedisUtils;
import top.xia17.plugins.fast.common.exceptions.BadRequestException;
import top.xia17.plugins.fast.common.security.token.provider.TokenProvider;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.xia17.plugins.fast.auth.autoconfiguraion.AuthProperties;
import top.xia17.plugins.fast.auth.model.AuthConstant;
import top.xia17.plugins.fast.auth.model.req.UsernameLoginReq;
import top.xia17.plugins.fast.user.model.dto.UserDto;
import top.xia17.plugins.fast.user.service.UserService;


/**
 * 用户名密码登录helper
 * @author xia17
 * @since 2022/6/1 11:45
 */
@Service
public class UsernameLoginHelper extends AbstractLoginHelper<UsernameLoginReq> {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;

    @SuppressWarnings("all")
    public UsernameLoginHelper(AuthProperties authProperties, RedisUtils redisUtils,
                               UserService userService, PasswordEncoder passwordEncoder ,
                               TokenProvider tokenProvider, TokenProperties tokenProperties) {
        super(authProperties, redisUtils, userService, tokenProvider, tokenProperties);
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
    }

    @Override
    public String getLoginMethodName() {
        return AuthConstant.USERNAME_LOGIN_METHOD;
    }

    @Override
    public String getNotSupportErrorMessage() {
        return "系统已关闭用户名登录方式，请尝试其他登录方式！";
    }

    @Override
    public UserDto verifyUser(UsernameLoginReq req) {
        UserDto user = userService.getByUsername(req.getUsername()).orElseThrow(() -> new BadRequestException(
                "用户名或密码错误!"));
        if (!passwordEncoder.matches(req.getPassword(), user.getPassword())) {
            throw new BadRequestException("用户名或密码错误!");
        }
        return user;
    }
}
